/*
 * BenderView.java
 */
package bender;

import bender.appl.networks.RedBender;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import org.joone.engine.NeuralNetEvent;
import org.joone.engine.NeuralNetListener;
import org.joone.net.NeuralNet;

/**
 * The application's main frame.
 */
public class BenderView extends FrameView implements NeuralNetListener,Serializable {

    JFileChooser fc = new JFileChooser();
    private Date inicioEntrenamiento;
    private Date finEntrenamiento;
    private int cantidadCiclos;

    public BenderView(SingleFrameApplication app) {
        super(app);
        initComponents();
        iniciarRed();
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = BenderApp.getApplication().getMainFrame();
            aboutBox = new BenderAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        BenderApp.getApplication().show(aboutBox);
    }

    @Action
    public void showReconocerDlg() {
        if (reconocerDlg == null) {
            JFrame mainFrame = BenderApp.getApplication().getMainFrame();
            reconocerDlg = new ReconocerDlg(mainFrame, true);
            reconocerDlg.setLocationRelativeTo(mainFrame);
        }
        BenderApp.getApplication().show(reconocerDlg);
    }

    @Action
    public void guardar() throws IOException {
        BenderApp.getApplication().getRed().guardar("redBender.red");
    }

    @Action
    public void cargar() throws IOException, ClassNotFoundException {
        BenderApp.getApplication().setRed(RedBender.cargarRed(this, "redBender.red"));
    }

    private void guardarPesos() {
        BenderApp.getApplication().getRed();
    }

    private void iniciarRed() {
        BenderApp.getApplication().setRed(new RedBender(this));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtArchivo = new javax.swing.JTextField();
        btnArchivo = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cmbPosicion = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        btnAgregar = new javax.swing.JButton();
        btnEntrenar = new javax.swing.JButton();
        txtEstadoRed = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jSpinner1 = new javax.swing.JSpinner();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        itmGuardar = new javax.swing.JMenuItem();
        itmReconocer = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();

        mainPanel.setMaximumSize(new java.awt.Dimension(487, 410));
        mainPanel.setMinimumSize(new java.awt.Dimension(487, 410));
        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(bender.BenderApp.class).getContext().getResourceMap(BenderView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        txtArchivo.setEditable(false);
        txtArchivo.setText(resourceMap.getString("txtArchivo.text")); // NOI18N
        txtArchivo.setAutoscrolls(false);
        txtArchivo.setName("txtArchivo"); // NOI18N

        btnArchivo.setLabel(resourceMap.getString("buscarArchivoButton.label")); // NOI18N
        btnArchivo.setName("buscarArchivoButton"); // NOI18N
        btnArchivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnArchivoActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        cmbPosicion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" }));
        cmbPosicion.setEditor(null);
        cmbPosicion.setName("cmbPosicion"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Posición", "Path Archivo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.setName("tabla"); // NOI18N
        jScrollPane1.setViewportView(tabla);
        tabla.getColumnModel().getColumn(0).setMinWidth(55);
        tabla.getColumnModel().getColumn(0).setPreferredWidth(55);
        tabla.getColumnModel().getColumn(0).setMaxWidth(55);
        tabla.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tabla.columnModel.title0")); // NOI18N
        tabla.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tabla.columnModel.title1")); // NOI18N

        btnAgregar.setText(resourceMap.getString("agregarBoton.text")); // NOI18N
        btnAgregar.setName("agregarBoton"); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEntrenar.setText(resourceMap.getString("btnEntrenar.text")); // NOI18N
        btnEntrenar.setName("btnEntrenar"); // NOI18N
        btnEntrenar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEntrenarActionPerformed(evt);
            }
        });

        txtEstadoRed.setText(resourceMap.getString("txtEstadoRed.text")); // NOI18N
        txtEstadoRed.setEnabled(false);
        txtEstadoRed.setName("txtEstadoRed"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jSpinner1.setName("jSpinner1"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 763, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(cmbPosicion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(txtArchivo, javax.swing.GroupLayout.DEFAULT_SIZE, 737, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(btnEntrenar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtEstadoRed, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(btnAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 506, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnArchivo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbPosicion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregar)
                    .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEntrenar)
                    .addComponent(txtEstadoRed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setLabel(resourceMap.getString("archivoMenu.label")); // NOI18N
        fileMenu.setName("archivoMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(bender.BenderApp.class).getContext().getActionMap(BenderView.class, this);
        itmGuardar.setAction(actionMap.get("guardar")); // NOI18N
        itmGuardar.setText(resourceMap.getString("itmGuardar.text")); // NOI18N
        itmGuardar.setName("itmGuardar"); // NOI18N
        fileMenu.add(itmGuardar);

        itmReconocer.setAction(actionMap.get("showReconocerDlg")); // NOI18N
        itmReconocer.setLabel(resourceMap.getString("reconocerMenuItem.label")); // NOI18N
        itmReconocer.setName("reconocerMenuItem"); // NOI18N
        fileMenu.add(itmReconocer);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setToolTipText(resourceMap.getString("salirMenuItem.toolTipText")); // NOI18N
        exitMenuItem.setLabel(resourceMap.getString("salirMenuItem.label")); // NOI18N
        exitMenuItem.setName("salirMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setLabel(resourceMap.getString("ayudaMenu.label")); // NOI18N
        helpMenu.setName("ayudaMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setToolTipText(resourceMap.getString("acercaDetMenuItem.toolTipText")); // NOI18N
        aboutMenuItem.setName("acercaDetMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        /*if (txtArchivo.getText() != null && !txtArchivo.getText().equals("")) {
        txtEstadoRed.setText("");
        DefaultTableModel modelo = (DefaultTableModel) tabla.getModel();
        Object seleccionado = cmbPosicion.getSelectedItem();
        Integer posicion = new Integer(seleccionado.toString());
        Object[] columna = {posicion, txtArchivo.getText()};
        cmbPosicion.removeItem(seleccionado);
        modelo.addRow(columna);
        BenderApp.getApplication().getRed().agregarEntrenamiento(txtArchivo.getText(), posicion);
        txtArchivo.setText("");
        }
        else{
        txtEstadoRed.setText("Debe seleccionar un archivo...");
        }*/
        for (int i = 1; i <= 20; i++) {
            BenderApp.getApplication().getRed().agregarEntrenamiento("C:\\Documents and Settings\\Ramiro\\My Documents\\templates\\template_" + i + ".txt", new Integer(i - 1));
        }
}//GEN-LAST:event_btnAgregarActionPerformed

    private void btnArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnArchivoActionPerformed

        int returnVal = fc.showOpenDialog(this.btnAgregar);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File archivo = fc.getSelectedFile();
            txtArchivo.setText(archivo.getAbsolutePath());
            fc = new JFileChooser(archivo.getParent());

        }

    }//GEN-LAST:event_btnArchivoActionPerformed

    private void btnEntrenarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEntrenarActionPerformed
        try {
            BenderApp.getApplication().getRed().entrenar((Integer)jSpinner1.getValue());
        } catch (IOException ex) {
            txtEstadoRed.setText(ex.toString());
        }
    }//GEN-LAST:event_btnEntrenarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnArchivo;
    private javax.swing.JButton btnEntrenar;
    private javax.swing.JComboBox cmbPosicion;
    private javax.swing.JMenuItem itmGuardar;
    private javax.swing.JMenuItem itmReconocer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField txtArchivo;
    private javax.swing.JTextField txtEstadoRed;
    // End of variables declaration//GEN-END:variables
    private JDialog aboutBox;
    private JDialog reconocerDlg;

    public void netStarted(NeuralNetEvent e) {
        menuBar.setEnabled(false);
        btnAgregar.setEnabled(false);
        btnEntrenar.setEnabled(false);
        cantidadCiclos = 0;
        inicioEntrenamiento = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
        txtEstadoRed.setText(formatter.format(inicioEntrenamiento)
                + " Iniciando Red: ");
    }

    public void cicleTerminated(NeuralNetEvent e) {
        cantidadCiclos++;
        txtEstadoRed.setText("Terminado el ciclo: " + cantidadCiclos);
    }

    public void netStopped(NeuralNetEvent e) {
        finEntrenamiento = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
        txtEstadoRed.setText(formatter.format(inicioEntrenamiento) + "-" + 
                formatter.format(finEntrenamiento) + " Terminada Red con " +
                cantidadCiclos + " ciclos");
        menuBar.setEnabled(true);
        btnAgregar.setEnabled(true);
        btnEntrenar.setEnabled(true);
        guardarPesos();
    }

    public void errorChanged(NeuralNetEvent e) {
        ;
    }

    public void netStoppedError(NeuralNetEvent e, String error) {
        ;
    }
}
